
package com.haiyou.common.file;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

import org.apache.commons.lang3.Validate;
import org.springframework.util.StringUtils;

import com.haiyou.common.event.asyc.AsyncEventBuses;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: 文件监听器,只能监听文件夹,收取文件变动事件FileModifiedEvent[WatchEvent[?]]处理后续逻辑
 * @author xingyuan
 * @date 2022年2月15日 下午5:11:30
 */
@Slf4j
public class FileWatcher {

	private static WatchService watcher;

	static {
		new Thread(() -> {
			try {
				watcher = FileSystems.getDefault().newWatchService();
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
			for (;;) {
				try {
					WatchKey watchKey = watcher.take();
					List<WatchEvent<?>> watchEvents = watchKey.pollEvents();
					AsyncEventBuses.getInstance().postEvent(new FileModifiedEvent(watchEvents));
					if (!watchKey.reset()) {
						break;
					}
				} catch (InterruptedException e) {
					log.error(e.getMessage(), e);
					break;
				}
			}
		}).start();
	}

	public static boolean watchDir(String fileDir) {
		Validate.isTrue(!StringUtils.hasLength(fileDir));
		File file = new File(fileDir);
		Validate.isTrue(file.exists(), "文件[%s]不存在", file);
		Validate.isTrue(file.isDirectory(), "文件[%s]不是目录", file);
		Path path = Paths.get(fileDir);
		try {
			// 值监听变化
			path.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
			return true;
		} catch (IOException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public static void main(String[] args) {
		FileWatcher.watchDir("./src/main/resources");
	}

}
